/**
 * Created by yanyuan on 2014/12/2.
 */

angular.module('myApp.ContactHandler', ["myApp.DataStore", "myApp.GroupHandler", "myApp.ContactModel"])
    .factory("ContactHandler", ["$rootScope", "DataStore" , "GroupHandler", "Contact", "$http", "$q",
        function ($rootScope, DataStore, GroupHandler, Contact, $http, $q) {

            var saveContact = function(contact){
                DataStore.saveContact(contact);
            }

            var saveGroupContacts = function(groupIdentifier, contactIdentifiers){
                DataStore.saveGroupContacts(groupIdentifier, contactIdentifiers);
            }

            var saveGroupContact = function(groupIdentifier, contactIdentifier){
                DataStore.saveGroupContact(groupIdentifier, contactIdentifier);
            }

            var deleteGroupContact = function(groupIdentifier, contactIdentifier){
                DataStore.deleteGroupContact(groupIdentifier, contactIdentifier);
            }

            var deleteContact = function(contactIdentifier){
                DataStore.deleteContact(contactIdentifier);
            }

            var getContacts = function(){
                return DataStore.getContacts();
            }

            var getContactsByIdentifiers = function(identifiers){
                var contacts = [];
                angular.forEach(identifiers, function(identifier){
                    if(getContact(identifier) == null || getContact(identifier).identifier == null){
                        return;
                    }
                    contacts.push(getContact(identifier));
                });
                return contacts;
            }

            var contactIsExistGroup = function(groupIdentifier, contactIdentifier){
                if(getGroupContacts(groupIdentifier) == null) return false;
                return getGroupContacts(groupIdentifier).contains(contactIdentifier);
            }

            var getContact = function(identifier){
                return DataStore.getContact(identifier) == null ? {} : DataStore.getContact(identifier);
            }

            var getContactMap = function(){
                return DataStore.getContactMap();
            }

            var getGroupContacts = function(groupIdentifier){
                var contacts = [];
                var contactIdentifiers = DataStore.getGroupContacts()[groupIdentifier];
                angular.forEach(contactIdentifiers, function(identifier){
                    if(getContact(identifier) == null || getContact(identifier).identifier == null){
                        return;
                    }
                    contacts.push(getContact(identifier));
                });
                return contacts;
            }

            var groupContactsIsExist = function(groupIdentifier){
                return DataStore.getGroupContacts()[groupIdentifier];;
            }

            //获取群组联系人
            var getContactsByGroupPromise = function(groupIdentifier, useCache){
                var deferred = $q.defer();
                if(useCache && groupContactsIsExist(groupIdentifier)){
                    deferred.resolve(getGroupContacts(groupIdentifier));
                }else{
                    queryContactsByGroupPromise({"groupIdentifier" : groupIdentifier}).then(function(groupContacts){
                        var contactIdentifiers = [];
                        angular.forEach(groupContacts, function(contact){
                            contactIdentifiers.push(contact.identifier);
                        });
                        saveGroupContacts(groupIdentifier, contactIdentifiers);
                        deferred.resolve(getContactsByIdentifiers(contactIdentifiers));
                    }, function(errorMsg){
                        deferred.reject(errorMsg);
                    });
                }
                return deferred.promise;
            }

            //API查询群组联系人
            var queryContactsByGroupPromise = function(paramData){
                var deferred = $q.defer();
                $http({
                    method: "POST",
                    url: "group/listUser.do",
                    data: $.param(paramData),
                    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (data) {
                    if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                        util.tokenExpire();
                        return;
                    }
                    if(data.error){
                        deferred.reject(data.error);//申明执行失败
                    }
                    angular.forEach(data.result, function(contact){
                       contact.identifier = contact.username;
                    });
                    deferred.resolve(data.result);//声明执行成功，且返回数据
                }).error(function () {
                    deferred.reject("请求服务器失败！");
                });
                return deferred.promise; //返回执行状态
            }

            //星标联系人操作（增加/删除）
            var commonlyUsedContacterPromise = function(paramData){
                var deferred = $q.defer();
                $http({
                    method : 'POST',
                    url : 'contact/commonlyUsedContacter.do',
                    data : $.param(paramData),
                    headers : {'Content-Type': 'application/x-www-form-urlencoded'}
                }).success(function(data){
                    if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                        util.tokenExpire();
                        return;
                    }
                    if(data.error){
                        deferred.reject(data.error);
                    }
                    deferred.resolve(data.result);
                }).error(function(){
                    deferred.reject("请求服务器失败！");
                });
                return deferred.promise;
            }

            //查询常用联系人
            var queryCommonlyUsedContacterPromise = function(){
                var deferred = $q.defer();
                $http({
                    method : 'POST',
                    url : 'contact/queryCommonlyUsedContacter.do',
                    headers : {'Content-Type': 'application/x-www-form-urlencoded'}
                }).success(function(data){
                    if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                        util.tokenExpire();
                        return;
                    }
                    if(data.error){
                        deferred.reject(data.error);
                    }
                    deferred.resolve(data.result);
                }).error(function(){
                    deferred.reject("查询星标联系人失败！");
                });
                return deferred.promise;
            }

            var refreshContact = function(){
                $rootScope.contactMap = getContactMap();
                $rootScope.contacts = getContacts();
            }

            var contactIsExist = function(identifier){
                return DataStore.getContact(identifier) == null ? false : true;
            }

            return {
                saveGroupContacts : saveGroupContacts,
                saveGroupContact : saveGroupContact,
                deleteGroupContact : deleteGroupContact,
                contactIsExistGroup : contactIsExistGroup,
                saveContact : saveContact,
                deleteContact : deleteContact,
                getContact : getContact,
                getContactMap : getContactMap,
                getContacts : getContacts,
                getContactsByGroupPromise : getContactsByGroupPromise,
                commonlyUsedContacterPromise : commonlyUsedContacterPromise,
                queryCommonlyUsedContacterPromise : queryCommonlyUsedContacterPromise,
                refreshContact :refreshContact,
                contactIsExist : contactIsExist
            }
        }]);